package com.pp.ent.view;

import com.pp.ent.base.log.MLog;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * Author:dengqu
 * Date:2016/7/26
 */
public class DynamicHandler implements InvocationHandler {
    private final static String TAG = "DynamicHandler";
    private WeakReference<Object> handlerRef;
    private final HashMap<String, Method> methodMap = new HashMap<String, Method>(
            1);

    public DynamicHandler(Object handler) {
        this.handlerRef = new WeakReference<Object>(handler);
    }

    public void addMethod(String name, Method method) {
        methodMap.put(name, method);
    }

    public Object getHandler() {
        return handlerRef.get();
    }

    public void setHandler(Object handler) {
        this.handlerRef = new WeakReference<Object>(handler);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        Object handler = handlerRef.get();
        if (handler != null) {
            String methodName = method.getName();
            method = methodMap.get(methodName);
            method.setAccessible(true);
            if (method != null) {
                try {
                    return method.invoke(handler, args);
                } catch (IllegalAccessException e) {
                    MLog.error(TAG, e);
                } catch (InvocationTargetException e) {
                    MLog.error(TAG, e);
                }
            }
        }
        return null;
    }
}
